package dev.touchswipe.shared.Animation
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	[Event(name="startAnimation", type="dev.touchswipe.shared.Animation.AnimationEvent")]
	[Event(name="animationUpdate", type="dev.touchswipe.shared.Animation.AnimationEvent")]
	[Event(name="stopAnimation", type="dev.touchswipe.shared.Animation.AnimationEvent")]
	
	public class Animation extends EventDispatcher
	{
		private static var _timingSprite:Sprite=new Sprite();
		
		private var _start:Number;
		private var _end:Number;
		private var _duration:Number;
		private var _target:Object;
		private var _property:String;
		private var _step:int=0;
		public var autoStop:Boolean=true;
		
		public function Animation(target:Object,property:String,startValue:Number,endValue:Number,duration:int)
		{
			_start=startValue;
			_end=endValue;
			_duration=duration;
			_target=target;
			_property=property;
		}
		
		public function start():void{
			_step=0;
			_timingSprite.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			_target[_property]=_start;
			dispatchEvent(new AnimationEvent(AnimationEvent.START_ANIMATION,0));
		}
		
		private function onEnterFrame(event:Event):void{
			/*if(_target[_property]!=_start+(_end-_start)*_step/_duration){
				stop();
				return;
			}*/
			_step++;
			if(_step<=_duration){
				_target[_property]=_start+(_end-_start)*_step/_duration;
				dispatchEvent(new AnimationEvent(AnimationEvent.ANIMATION_UPDATE,_step/_duration));
			}
			else{
				stop();
			}
		}
		
		public function stop():void{
			_timingSprite.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
			dispatchEvent(new AnimationEvent(AnimationEvent.STOP_ANIMATION,_step/_duration));
		}
		
		public static function makeCallbackAnimation(callBack:Function,thisObj:Object,startValue:Number,endValue:Number,duration:int):Animation{
			var _object:Object=new Object();
			_object._property=null;
			var anim:Animation=new Animation(_object,"_property",startValue,endValue,duration);
			anim.addEventListener(AnimationEvent.ANIMATION_UPDATE,function (e:AnimationEvent):void{
				callBack(thisObj,_object._property);
			});
			return anim;
		}
	}
}